trigger hcpEffectiveDateTrigger on HCP__c (after update) {

    //判断是否进入代码段
    boolean b=false;
    for(HCP__c h:trigger.new){
        if(Trigger.oldMap.get(h.Id).effectivedate__c != h.effectivedate__c &&(h.effectivedate__c!=null) ){
            b=true;
        }
    }
    if(b){
    //搜索出所有医护人员
    list<id> hcpid=new list<id>();
    for(HCP__c h:trigger.new){
        hcpid.add(h.id);
    }
    list<HCP__c> hcpl=[select id,approvalstatus__c,Effectivedate__c from HCP__c where id in:hcpid];
   
    //清空医护人员审批状态  用以清除工作流
    for(HCP__c h:hcpl){
        if(h.effectivedate__c!=null){
            h.approvalstatus__c='';
        }
    }
    update hcpl;
    //重新填入审批状态
    for(HCP__c h:hcpl){
        if(h.effectivedate__c!=null){
            h.approvalstatus__c='审批通过但未生效';
        }
    }
    update hcpl;
    //搜索出所有触发HCP生效记录
    list<HCPEffectiveTrigger__c> hedtl=[select id from HCPEffectiveTrigger__c where HCP__c in:hcpid];
    //删除所有触发HCP生效记录  用以清除工作流
    delete hedtl;
    //重新插入触发HCP生效记录
    list<HCPEffectiveTrigger__c> insertl=new list<HCPEffectiveTrigger__c>();
    for(HCP__c h:trigger.new){
         HCPEffectiveTrigger__c hedt=new HCPEffectiveTrigger__c(name=h.Name,HCP__c=h.id,effectivedate__c=h.effectivedate__c);
         insertl.add(hedt);
    }
    insert insertl;
    }
    

/*
List<HCP__c> hcpl=new List<HCP__c>();
List<HCPEffectiveTrigger__c> hetl=new List<HCPEffectiveTrigger__c>();
    for(HCP__c h:trigger.new){
      if(Trigger.OldMap.get(h.id).effectivedate__c!=h.effectivedate__c && h.effectivedate__c!=null){
        hcpl=[select id,approvalstatus__c,effectivedate__c from HCP__c where id=:h.id];
        hetl=[select id from HCPEffectiveTrigger__c where HCP__c=:h.id];
       if(hcpl.size()>0){
        HCP__c hcp=hcpl[0];
        hcp.approvalstatus__c='';
        update hcp;
        hcp.approvalstatus__c='审批通过但未生效';
        update hcp;
        if(hetl.size()>0){
         delete hetl;
        }
        HCPEffectiveTrigger__c hcpe=new HCPEffectiveTrigger__c(name=h.Name,HCP__c=h.id,effectivedate__c=h.effectivedate__c);
        insert hcpe;
       } 
       
      }
    }*/
}